package classxuliehua;

import java.io.*;
import java.util.Objects;

public class ObjInStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //创建对象
        Person p = new Person("张三", 18);
        //创建流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day10-code/src/classxuliehua/person.dat"));
        //写出对象
        oos.writeObject(p);
        //关闭流
        oos.close();

        //创建流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day10-code/src/classxuliehua/person.dat"));
        //读取对象
        Person person = (Person) ois.readObject();
        //也可以进行修改
        person.setName("小王");
        //显示
        System.out.println(person);

        ois.close();

    }
}
class Person implements Serializable {

    @Serial
    private static final long serialVersionUID = -8589826161165539061L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}